package com.app.studyroom;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.model.ssrUser.RegisterRequest;
import com.app.studyroom.mapper.AreaNameToIdMapper;
import com.app.studyroom.utils.FileUtils;

import java.io.File;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AccountRegisterActivity extends BaseActivity {

    private EditText editPhone, editNewPassword, editConfirmPassword, editID, editStudentID,editClassID, editUserName;
    private Button btnRegister;
    private TextView tvLogin;
    private ImageView image_back, imgAvatar;
    private Spinner spinnerArea;

    private String selectedArea = "";
    private static final int REQUEST_CODE_PICK_IMAGE = 1001;
    private Uri selectedAvatarUri = null;        // 用户选中的头像 URI
    private String uploadedImageId = null;       // 上传成功后返回的头像 ID
    private LinearLayout layoutHide;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_register);

        editPhone = findViewById(R.id.editPhone);
        editNewPassword = findViewById(R.id.editNewPassword);
        editConfirmPassword = findViewById(R.id.editConfirmPassword);
        editID = findViewById(R.id.editID);
        editStudentID = findViewById(R.id.editStudentID);
        editClassID = findViewById(R.id.editClassID);
        editUserName = findViewById(R.id.editUserName);
        btnRegister = findViewById(R.id.btnRegister);
        tvLogin = findViewById(R.id.tv_Login);
        image_back = findViewById(R.id.ic_back);
        spinnerArea = findViewById(R.id.spinnerArea);
        imgAvatar = findViewById(R.id.img_avatar);
        //隐藏
        layoutHide = findViewById(R.id.layout_hide);
        layoutHide.setVisibility(View.GONE);

        imgAvatar.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "选择头像"), REQUEST_CODE_PICK_IMAGE);
        });

        btnRegister.setOnClickListener(v -> handleRegister());

        tvLogin.setOnClickListener(v -> {
            Intent intent = new Intent(this, AccountLoginActivity.class);
            intent.putExtra("identity", "user");
            startActivity(intent);
            overridePendingTransition(0, 0);
            finish();
        });

        image_back.setOnClickListener(v -> {
            Intent intent = new Intent(this, AccountLoginActivity.class);
            startActivity(intent);
            overridePendingTransition(0, 0);
            finish();
        });


        //这里没有映射区域数，是自己给的区域，但是现在用户不需要区域这个参数了，后面需要的话切记要调一下区域树的mapper
        String[] areas = {"A校区01自习室", "A校区02自习室", "A校区03自习室", "B校区01自习室", "B校区02自习室"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.spinner_item, R.id.spinner_item_text, areas);
        adapter.setDropDownViewResource(R.layout.spinner_item);
        spinnerArea.setAdapter(adapter);
        spinnerArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    selectedArea = "";  // 未选择任何区域
                } else {
                    selectedArea = areas[position];
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                selectedArea = "";
            }
        });

    }

    private void handleRegister() {
        if (selectedAvatarUri == null) {
            Toast.makeText(this, "请选择头像", Toast.LENGTH_SHORT).show();
            return;
        }
        // 头像未上传但用户已选择 → 先上传
        if ( uploadedImageId == null) {
            uploadImage(selectedAvatarUri);
        } else {
            register(); // 注册
        }
    }

    private void register() {
        String userName = editUserName.getText().toString().trim();
        String idCard = editID.getText().toString().trim();
        String phone = editPhone.getText().toString().trim();
        String studentId = editStudentID.getText().toString().trim();
        String classId = editClassID.getText().toString().trim();
        String password = editNewPassword.getText().toString().trim();
        String confirmPassword = editConfirmPassword.getText().toString().trim();

        if (idCard.isEmpty() || phone.isEmpty() || studentId.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
            Toast.makeText(this, "请完整填写所有信息", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!password.equals(confirmPassword)) {
            Toast.makeText(this, "两次密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        RegisterRequest request = new RegisterRequest();
        request.setUserZjh(idCard);
        request.setUserSjh(phone);
        request.setUserNumber(studentId);
        request.setClassNum(classId);
        request.setUserPassword(password);
        request.setUserName(userName);
        request.setUserBs("用户");
        request.setQy(AreaNameToIdMapper.getIdByName(selectedArea));
        request.setUserImage(uploadedImageId);

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<ApiResponse<Object>> call = apiService.register(request);
        call.enqueue(new Callback<ApiResponse<Object>>() {
            @Override
            public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    Toast.makeText(AccountRegisterActivity.this, "注册成功，请登录", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(AccountRegisterActivity.this, AccountLoginActivity.class));
                    finish();
                } else {
                    String msg = response.body() != null ? response.body().getMessage() : "未知错误";
                    Toast.makeText(AccountRegisterActivity.this, "注册失败：" + msg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                Toast.makeText(AccountRegisterActivity.this, "网络连接失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void uploadImage(Uri uri) {
        File file = FileUtils.getFileFromUri(this, uri);
        if (file == null) {
            Toast.makeText(this, "文件无效", Toast.LENGTH_SHORT).show();
            return;
        }

        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<ApiResponse<Map<String, String>>> call = apiService.uploadImage(body);
        call.enqueue(new Callback<ApiResponse<Map<String, String>>>() {
            @Override
            public void onResponse(Call<ApiResponse<Map<String, String>>> call, Response<ApiResponse<Map<String, String>>> response) {
                if (response.isSuccessful() && response.body().getCode() == 200) {
                    uploadedImageId = response.body().getData().get("id");
//                    Toast.makeText(AccountRegisterActivity.this, "头像上传成功", Toast.LENGTH_SHORT).show();  //测试用
                    register(); // 上传成功后调用注册
                } else {
                    Toast.makeText(AccountRegisterActivity.this, "头像上传失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Map<String, String>>> call, Throwable t) {
                Toast.makeText(AccountRegisterActivity.this, "头像上传失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == RESULT_OK && data != null) {
            selectedAvatarUri = data.getData();        // 保存选中的 URI
            imgAvatar.setImageURI(selectedAvatarUri);  // 只做预览，不上传
        }
    }
}
